/*
 * @Author: mikey.zhaopeng 
 * @Date: 2019-10-04 13:34:26 
 * @Last Modified by: mikey.zhaopeng
 * @Last Modified time: 2019-10-05 14:42:29
 管理相册
 */

<template>
  <div>
    <el-container style="position:absolute;top:55px;left:0;right:0;bottom:0;">
      <!-- 头部 -->
      <el-header class="d-flex align-items-center">
        <div class="d-flex mr-auto">
          <el-select v-model="serachForm.order" placeholder="请选择图片排序方式" size="medium" class="mr-2">
            <el-option label="区域一" value="one"></el-option>
            <el-option label="区域二" value="two"></el-option>
          </el-select>
          <el-input v-model="serachForm.keyword" placeholder="请输入相册名称" size="medium" class="mr-2">></el-input>
          <el-button type="primary" size="medium">搜索</el-button>
        </div>
        <div>
          <el-button
            type="warning"
            @click="unChoose({all:true})"
            size="mini"
            v-if="chooseList.length"
          >取消选中</el-button>
          <el-button
            type="danger"
            @click="imageDel({all:true})"
            size="mini"
            v-if="chooseList.length"
          >批量删除</el-button>
          <el-button type="success" @click="openAlbumModel(false)" size="mini">创建相册</el-button>
          <el-button type="warning" @click="uploadModel=true" size="mini">上传图片</el-button>
        </div>
      </el-header>
      <el-container>
        <!-- 侧栏 -->
        <el-aside
          width="200px"
          style="position:absolute;top:60px;left:0;right:0;bottom:60px;"
          class="bg-white border-right"
        >
          <ul class="list-group list-group-flush">
            <!-- 引入组件左侧相册菜单  -->
            <album-item
              v-for="(item,index) in albums"
              :key="index"
              :item="item"
              :index="index"
              :active="albumIndex===index"
              @edit="openAlbumModel"
              @albumDel="albumDel"
            ></album-item>
          </ul>
        </el-aside>
        <el-container>
          <!-- 相册内容 -->
          <el-main style="position:absolute;top:60px;left:200px;right:0;bottom:60px; ">
            <el-row :gutter="10">
              <el-col
                :span="24"
                :lg="4"
                :md="6"
                :sm="8"
                v-for="(item,index) in imagesList"
                :key="index"
              >
                <el-card
                  shadow="hover"
                  class="box-card mb-3 position-relative"
                  :body-style="{'padding':'0'}"
                  style="cursor:pointer"
                >
                  <div class="border" :class="{'border-danger':item.isCheck}">
                    <span
                      class="badge badge-danger"
                      style="position:absolute;right:0;top:0;"
                      v-if="item.isCheck"
                    >{{item.checkOrder}}</span>
                    <img :src="item.url" class="w-100" style="height: 100px;" @click="choose(item)" />
                    <div
                      class="w-100 text-white px-1"
                      style="background:rgba(0,0,0,0.5);margin-top:-25px;position:absolute;"
                    >
                      <span class="small">{{item.name}}</span>
                    </div>
                    <div class="w-100 text-center p-2">
                      <el-button-group>
                        <el-button
                          icon="el-icon-view"
                          size="mini"
                          class="p-2"
                          @click="previewImage(item)"
                        ></el-button>
                        <el-button
                          icon="el-icon-edit"
                          size="mini"
                          class="p-2"
                          @click="imageEdit(item,index)"
                        ></el-button>
                        <el-button
                          icon="el-icon-delete"
                          size="mini"
                          class="p-2"
                          @click="imageDel({index})"
                        ></el-button>
                      </el-button-group>
                    </div>
                  </div>
                </el-card>
              </el-col>
            </el-row>
          </el-main>
        </el-container>
      </el-container>
      <!-- 底部分页 -->
      <el-footer class="d-flex align-items-center border-top px-0">
        <div
          style="width:200px;flex-shrink:0;"
          class="h-100 d-flex align-items-center justify-content-center border-right"
        >
          <el-button-group>
            <el-button size="mini">上一页</el-button>
            <el-button size="mini">下一页</el-button>
          </el-button-group>
        </div>
        <!-- 右侧分页 -->
        <div style="flex:1" class="px-2">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[100, 200, 300, 400]"
            :page-size="100"
            layout="total, sizes, prev, pager, next, jumper"
            :total="400"
          ></el-pagination>
        </div>
      </el-footer>
    </el-container>
    <!-- 修改/创建相册 -->
    <el-dialog :title="albumModelTitle" :visible.sync="albumModel" width="30%" center>
      <el-form ref="form" :model="albuForm" label-width="80px">
        <el-form-item label="相册名称">
          <el-input v-model="albuForm.name" size="medium" placeholder="相册名称"></el-input>
        </el-form-item>
        <el-form-item label="相册排序">
          <el-input-number v-model="albuForm.order" :min="0" size="medium"></el-input-number>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="albumModel = false">取 消</el-button>
        <el-button type="primary" @click="confirmAlbumModel">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 上传图片 -->
    <el-dialog title="上传图片" :visible.sync="uploadModel" width="40%" center>
      <div class="text-center">
        <el-upload
          class="upload-demo"
          drag
          action="https://jsonplaceholder.typicode.com/posts/"
          multiple
        >
          <i class="el-icon-upload"></i>
          <div class="el-upload__text">
            将文件拖到此处，或
            <em>点击上传</em>
          </div>
          <div class="el-upload__tip" slot="tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>
      </div>
    </el-dialog>
    <!--预览图片模态框  -->
    <el-dialog :visible.sync="previewModel" center width="90vh">
      <div style="margin:-60px -25px -30px -25px;">
        <img :src="previewUrl" alt class="w-100" />
      </div>
    </el-dialog>
  </div>
</template>

<script>
import albumItem from "@/components/image/album-item";
export default {
  name: "images",
  components: {
    albumItem
  },
  data() {
    return {
      // 分页
      currentPage: 1,
      //上传图片
      uploadModel: false,
      //预览图片模态框
      previewModel: false,
      serachForm: {
        order: "",
        keyword: ""
      },
      // 相册
      albums: [],
      albumIndex: 0, //始初相册选中的位置
      albumModel: false, //隐藏模态框
      albumEditIndex: -1, //-1创建相册
      albuForm: {
        name: "",
        order: 0
      },
      // 相册 列表
      imagesList: [],
      // 预览图片路径
      previewUrl: "",
      chooseList: [] //选中的序号
    };
  },

  computed: {
    // 动态修改相册title名称
    albumModelTitle() {
      return this.albumEditIndex > -1 ? "修改相册" : "创建相册";
    }
  },

  mounted() {
    this.__init();
  },

  methods: {
    __init() {
      for (var i = 1; i < 20; i++) {
        this.albums.push({
          name: "相册" + i,
          num: Math.floor(Math.random() * 100),
          order: 0
        });
      }
      for (var i = 0; i < 30; i++) {
        this.imagesList.push({
          id: i,
          url:
            "https://tangzhe123-com.oss-cn-shenzhen.aliyuncs.com/Appstatic/qsbk/demo/datapic/40.jpg",
          name: "图片" + i,
          isCheck: false,
          checkOrder: 0 //序号
        });
      }
    },
    // 点击左侧相册管理
    albumChange(index) {
      this.albumIndex = index; //点击给当前的下标赋值active
    },
    //删除相册事件
    albumDel(index) {
      this.$confirm("是否删除该相册?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          this.albums.splice(index, 1);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除"
          });
        });
    },
    // 修改和创建相框事件
    openAlbumModel(obj) {
      console.log(obj);
      //修改内容
      if (obj) {
        let { item, index } = obj;
        this.albuForm.name = item.name;
        this.albuForm.order = item.order;
        //修改状态下传入下标,用于确定事件判断是否为编辑状态
        this.albumEditIndex = index;
        this.albumModel = true;
        return;
      }
      //创建相册
      this.albuForm = {
        name: "",
        order: 0
      };
      this.albumEditIndex = -1;
      this.albumModel = true;
    },
    //相册模态框确定事件
    confirmAlbumModel() {
      //判断是否为修改按钮>-1为修改
      if (this.albumEditIndex > -1) {
        this.albumEdit();
        this.albumModel = false;
        return;
      }
      // 创建相册,追加
      this.albums.unshift({
        name: this.albuForm.name,
        order: this.albuForm.order,
        num: 0
      });
      this.albumModel = false;
    },
    //修改相册
    albumEdit() {
      this.albums[this.albumEditIndex].name = this.albuForm.name;
      this.albums[this.albumEditIndex].order = this.albuForm.order;
    },
    //选中相片
    choose(item) {
      //加入选中数组中
      // 选中状态
      if (!item.isCheck) {
        this.chooseList.push({
          id: item.id,
          url: item.url
        });
        // 计算序号
        item.checkOrder = this.chooseList.length;
        // 修改状态
        item.isCheck = true;
        return;
      }
      // 未选中状态/取消选中,找到对应的索引进行删除再删除长度
      //修改状态
      item.isCheck = false;
      // 重序号
      item.checkOrder = 0;
      //查找ID,findIndex()函数也是查找目标元素，找到就返回元素的位置，找不到就返回-1
      let i = this.chooseList.findIndex(v => v.id === item.id);
      if (i == -1) return; //没到就返回
      //如果找到进行删除需重新计算序号
      let length = this.chooseList.length;
      //如果取消中间的中就要重新计算序号,只计算当前选中的I之后的序号
      if (i + 1 < length) {
        for (let j = i; j < length; j++) {
          // 如果imagesList下的id和chooseList下的id相等就返回
          let no = this.imagesList.findIndex(
            v => v.id === this.chooseList[j].id
          );

          //如果返回有值,对之后的序号重新计算
          if (no > -1) {
            this.imagesList[no].checkOrder--;
          }
        }
      }
      // 找到就删除
      if (i != -1) {
        this.chooseList.splice(i, 1);
      }
      if (item.id == this.chooseList) {
      }
    },
    // 预览图片
    previewImage(item) {
      this.previewUrl = item.url;
      this.previewModel = true;
    },
    //编辑图片
    imageEdit(item, index) {
      this.$prompt("请输入新名称", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        inputValue: item.name,
        inputValidator(val) {
          if (val === "") {
            return "图片名不能为空";
          }
        }
      })
        .then(({ value }) => {
          item.name = value;
          this.$message({
            type: "success",
            message: "修改成功"
          });
        })
        .catch(() => {});
    },
    // 删除当前图片/批量删除
    imageDel(obj) {
      console.log(obj);
      this.$confirm(obj.all ? "是否删除选中图片" : "是否删除该图片?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        if (obj.all) {
          /**
           * 批量删除
           *把imagesList中所有的Id和chooseList选中的id匹配把匹配到的也就是没选中的返回出去
           */
          let list = this.imagesList.filter(img => {
            return !this.chooseList.some(c => {
              return c.id === img.id;
            });
          });
          // 重新赋值
          this.imagesList = list;
          this.chooseList = [];
        } else {
          this.imagesList.splice(obj.index, 1);
        }
        this.$message({
          type: "success",
          message: "删除成功!"
        });
      });
    },
    // 取消选中
    unChoose() {
      this.imagesList.forEach(img => {
        // 找到所有选中图片返回索引 
        let i = this.chooseList.findIndex(item => {
          return item.id === img.id;
        });
        //取消选中样式
        img.isCheck = false;
        img.checkOrder = 0;
        // 从chooseList中移除
        this.chooseList.splice(i,1)
      });
    },
    //分页
    handleSizeChange(val) {
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
    }
  },

  watch: {}
};
</script>
<style  scoped>
/* 修改slide激活背景色 */
.sum-active {
  color: #67c23a !important;
  background: #f0f9eb !important;
  border-color: #c2e7b0 !important;
}
</style>